/********************************************************************************
 * @file    atcmd_slave.c
 * @author  jianqiang.xue
 * @version V1.1.0
 * @date    2022-11-13
 * @brief   从机版 AT指令 https://lisun.blog.csdn.net/article/details/126683930
 ********************************************************************************/

#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>

#include "atcmd_slave.h"

extern atcmd_info_t atcmd$$Base;
extern atcmd_info_t atcmd$$Limit;

bool atcmd_msg_handle(atcmd_pack_t* pack) {
    atcmd_info_t* atcmd;
    bool match = false;

    for (atcmd = &atcmd$$Base; atcmd < &atcmd$$Limit; atcmd++) {
        if (atcmd->name != (char *)0xffffffff) { // 针对flash默认值为0xfffffffff时，不进行比较
            if (strncmp((char*)(pack->data), atcmd->name, strlen(atcmd->name)) == 0) {
                if (strstr((char*)(pack->data), "=?") != 0) { // 防止错过
                    if (strstr((char*)(atcmd->name), "=?") != 0) { // 防止错过
                    } else {
                    continue;
                    }
                }
                match = true;
                break;
            }
        }
    }
    if (match) {
        // 裁剪  AT^XXXX=(保留)\r\n
        pack->len -= strlen(atcmd->name) - 2; // 2 == \r\n
        pack->data += strlen(atcmd->name); // 移除前面的内容,并包含'=' or '?' or '=?'
        pack->data[pack->len + 1] = '\0';
        atcmd->callback(pack);
        return 0;
    }
    return -1;
}

#ifdef ATCMD_EN
// 在功能模块中定义一个标准函数
static int test(atcmd_pack_t *pack) {
    uint8_t buff[20] = "test"AT_OK;
    pack->reply(buff, strlen((char*)buff));
    return 0;
}

static int test2(atcmd_pack_t *pack) {
    uint8_t buff[20] = "";
    uint32_t num = 0, num1 = 0;
    pack->argc = sscanf((char*)(pack->data), "%d,%d", &num, &num1);
    if (pack->argc != 2) return -1;
    snprintf((char*)buff, 20, "%d,%d"AT_OK, num, num1);
    pack->reply(buff, strlen((char*)buff));
    return 1;
}

// 注册AT指令，传入标准函数
ATCMD_INIT("AT+TEST?", test);
ATCMD_INIT("AT+TEST=", test2);
#endif
